<?php

require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Model/Meta.php';
require_once 'Pipes/Database/Reflection/Table.php';
require_once 'Pipes/Database/Reflection.php';
require_once 'Pipes/Model/Meta/Column.php';
require_once 'Pipes/Model/Relationship/Mapper.php';

class Pipes_Model_Meta implements PipesImpl_Model_Meta
{
    protected $_config = null;
    private $_table_name = '';
    protected $_columnOverrides = array();
    protected $_hasMany = array();

    private $_columns = array();
    
    public function __construct(PipesImpl_Config $config)
    {
        $this->_config = $config;
        
        $exploded = explode('_', get_class($this));
        $this->_table_name = strtolower(substr(array_pop($exploded), 0, -4)) . 's';
    }
    
    public function getColumns()
    {
        $this->_initColumns();
        return $this->_columns;
    }
    
    public function hasRelationship($name)
    {
        return in_array($name, $this->_hasMany);
    }
    
    public function getRelationship(PipesImpl_Model $model, $name) {
        $mapper = new Pipes_Model_Relationship_Mapper($this->_config, $model);
        return $mapper->getList($name);
    }
    
    public function listRelationships() {
        return $this->_hasMany;
    }

    public function idColumn() {
        $this->_initColumns();
        return $this->_columns[substr($this->_table_name, 0, -1) . '_id'];
    }

    private function _initColumns() {
        if (count($this->_columns) > 0) {
            return;
        }

        $reflection = new Pipes_Database_Reflection($this->_config);
        $table = $reflection->fetchTable($this->_table_name);            
        $columns = $table->getColumns();
        $returnArray = array();
        foreach ($columns as $column) {
            $columnOverrides = !empty($this->_columnOverrides[$column->getName()]) ?
                $this->_columnOverrides[$column->getName()] :
                array();
            $this->_columns[$column->getName()] = new Pipes_Model_Meta_Column($column, $columnOverrides);
        }
    }

}
